﻿Public Class VbRegexFormatter
    Implements IRegexFormatter

    Public Function Format(regex As String, options As System.Text.RegularExpressions.RegexOptions) As String Implements IRegexFormatter.Format
        Dim l_expressionBuilder As New Text.StringBuilder()

        Dim r As New System.Text.RegularExpressions.Regex(
            pattern:="",
            options:=
                RegexOptions.None And
                RegexOptions.Compiled
        )

        Dim l_namespace As String = "System.Text.RegularExpressions"
        Dim l_class As String = "Regex"
        Dim l_optionsEnum As String = "RegexOptions"

        l_expressionBuilder.Append(String.Format("Dim regex As New {0}.{1}", l_namespace, l_class))

        l_expressionBuilder.AppendLine("(")

        Dim l_regexLines = From l_regexPart In regex.Split(Environment.NewLine)
                           Select String.Format("{0}{1}{0}", ControlChars.Quote, l_regexPart.Replace(ControlChars.Quote, ControlChars.Quote & ControlChars.Quote))

        l_expressionBuilder.AppendLine(
            ControlChars.Tab & "pattern:=" & String.Join(" & Environment.NewLine &" & Environment.NewLine, l_regexLines.ToArray()) & ","
        )



        Dim l_optionNames =
            From l_regexOption In [Enum].GetValues(GetType(RegexOptions))
            Where (options And l_regexOption) > 0
            Select String.Format("{0}.{1}.{2}", l_namespace, l_optionsEnum, [Enum].GetName(GetType(RegexOptions), l_regexOption))

        Dim l_optionsList = String.Join(" And" & Environment.NewLine & ControlChars.Tab & ControlChars.Tab, l_optionNames.ToArray())
        If String.IsNullOrEmpty(l_optionsList) Then
            l_optionsList = String.Format("{0}.{1}.{2}", l_namespace, l_optionsEnum, [Enum].GetName(GetType(RegexOptions), RegexOptions.None))
        End If

        l_expressionBuilder.AppendLine(ControlChars.Tab & "options:=")
        l_expressionBuilder.AppendLine(ControlChars.Tab & ControlChars.Tab & l_optionsList)

        l_expressionBuilder.Append(")")

        Return l_expressionBuilder.ToString()
    End Function

End Class
